package com.yu.newsSys.dao.impl;

import com.yu.newsSys.dao.AdminDao;
import com.yu.newsSys.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class AdminDaoImpl implements AdminDao {

    // 检验输入账户是否已经存在
    @Override
    public int countByUserName(String username) {
        Connection conn = null;
        PreparedStatement prep = null;
        ResultSet rs = null;
        int count = 0;
        try {
            System.out.println("countByUserName from dao running");
            conn = JDBCUtils.getConnection();
            prep = conn.prepareStatement("select count(id) from admin where username =?");
            prep.setString(1,username);
            rs = prep.executeQuery();
            if (rs.next()) {
                count = rs.getInt(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(rs,prep,conn);
        }
        return count;
    }
    // 插入user数据
    @Override
    public int save(String username, String password) {
        Connection conn = null;
        PreparedStatement prep = null;
        ResultSet rs = null;
        // 返回受影响的行数
        int count = 0;
        try {
            System.out.println("save from dao running");
            conn = JDBCUtils.getConnection();
            prep = conn.prepareStatement("insert into admin(username,password)values (?,?)");
            prep.setString(1,username);
            prep.setString(2,password);
            count = prep.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(null,prep,conn);
        }
        return count;
    }

    @Override
    public int checkUser(String username, String password) {
        Connection conn = null;
        PreparedStatement prep = null;
        int count = 0;
        ResultSet rs = null;
        try {
            System.out.println("checkUser from dao running");
            conn = JDBCUtils.getConnection();
            prep = conn.prepareStatement("select count(id) from admin where username =? and password = ?");
            prep.setString(1,username);
            prep.setString(2,password);
            rs = prep.executeQuery();
            if (rs.next()) {
                count = rs.getInt(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(rs,prep,conn);
        }
        return count;
    }
}
